import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, Switch, message, Layout, Menu, Dropdown, Avatar, Upload, Select, InputNumber, Popconfirm, Drawer, Row, Col, Divider, Typography, Image } from 'antd';
import { PlusOutlined, CopyOutlined,EditOutlined, DeleteOutlined, SearchOutlined, UserOutlined, LogoutOutlined, UploadOutlined, MinusCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import useDeviceStore from '../store/deviceStore';
import useAuthStore from '../store/authStore';
import { useNavigate } from 'react-router-dom';
import { searchItems, createItem, updateItem, deleteItem, uploadImage, showItem } from '../services/api';

const { Header } = Layout;

const DeviceManagement = () => {
  const [form] = Form.useForm();
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [editingDevice, setEditingDevice] = useState(null);
  const [isCopy, setIsCopy] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [committedKeyword, setCommittedKeyword] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [deletingId, setDeletingId] = useState(null);
  const [hasMore, setHasMore] = useState(false);
  const [filterCateId, setFilterCateId] = useState();

  // 预览状态（封面）
  const [avatarPreviewOpen, setAvatarPreviewOpen] = useState(false);
  const [avatarPreviewImage, setAvatarPreviewImage] = useState('');
  const [avatarFileList, setAvatarFileList] = useState([]);
  const STATIC_IMAGE_BASE = 'https://api.saierzy.cn/v1/static/image/';

  // 预览状态（详情）
  const [detailPreviewOpen, setDetailPreviewOpen] = useState(false);
  const [detailPreviewImage, setDetailPreviewImage] = useState('');
  const [detailFileList, setDetailFileList] = useState([]);

  const toAbsoluteUrl = (val) => {
    if (!val) return '';
    const s = String(val).trim();
    if (/^https?:\/\//i.test(s)) return s;
    if (/^www\./i.test(s)) return `https://${s}`;
    return `${STATIC_IMAGE_BASE}${s}`;
  };

  // 构建提交payload：合并表单值 + 规范化字段 + 覆盖项
  const buildUpdatePayload = (overrides = {}) => {
    const values = form.getFieldsValue();
    const norm = {
      ...values,
      cate_id: values?.cate_id != null ? Number(values.cate_id) : undefined,
      is_show: values?.is_show ? 1 : 0,
    };
    return { ...norm, ...overrides };
  };

  // 将 URL 转为文件名（编辑时仅需 filename）
  const extractFilename = (val) => {
    if (!val) return '';
    try {
      const str = String(val);
      const parts = str.split('/');
      return parts[parts.length - 1] || str;
    } catch {
      return val;
    }
  };

  const confirmRemove = (fileLabel = '该图片') =>
    new Promise((resolve) => {
      Modal.confirm({
        title: '确认移除吗？',
        content: `确定要移除${fileLabel}吗？`,
        okText: '移除',
        cancelText: '取消',
        onOk: () => resolve(true),
        onCancel: () => resolve(false),
      });
    });

  const navigate = useNavigate();
  const { user, logout } = useAuthStore();

  // 动态标签：人物专访(cate_id=3) 时切换
  const watchedCateId = Form.useWatch('cate_id', form);
  const isInterview = Number(watchedCateId) === 3;

  const {
    devices,
    addDevice,
    editDevice,
    deleteDevice,
    toggleRecommended,
    toggleDisplayed
  } = useDeviceStore();

  const fetchList = async () => {
    setLoading(true);
    try {
      const { list: serverList, total: serverTotal, hasMore: serverHasMore } = await searchItems({
        keyword: committedKeyword,
        page: currentPage,
        size: pageSize,
        cate_id: filterCateId,
      });
      setList(serverList || []);
      setTotal(serverTotal || 0);
      setHasMore(!!serverHasMore);
    } catch (e) {
      message.error('获取列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchList();
  }, [currentPage, pageSize, committedKeyword, filterCateId]);

  const showModal = (device = null, isCopy = false) => {
    setEditingDevice(device);
    setIsCopy(isCopy);
    if (device) {
      const avatarFilename = extractFilename(device.avatar);
      const rawDetail = Array.isArray(device.detail_images)
        ? device.detail_images
        : (typeof device.detail_images === 'string' ? device.detail_images.split(',') : []);
      const detailImages = rawDetail
        .map((img) => extractFilename(img))
        .filter((s) => String(s || '').trim());
      // 处理 manufacturer 字段，确保是数组格式
      const manufacturerArray = Array.isArray(device.manufacturer) 
        ? device.manufacturer 
        : (device.manufacturer ? [String(device.manufacturer)] : ['']);
      
      form.setFieldsValue({
        ...device,
        manufacturer: manufacturerArray,
        avatar: avatarFilename,
        detail_images: detailImages.length ? detailImages : [''],
      });
      // 设置封面文件列表用于预览
      if (avatarFilename) {
        setAvatarFileList([
          { uid: '-1', name: avatarFilename, status: 'done', url: toAbsoluteUrl(avatarFilename) },
        ]);
      } else {
        setAvatarFileList([]);
      }
      // 设置详情文件列表用于预览
      if (detailImages && detailImages.length) {
        setDetailFileList(
          detailImages.map((fn, idx) => ({ uid: `d-${idx}`, name: fn, status: 'done', url: toAbsoluteUrl(fn) }))
        );
      } else {
        setDetailFileList([]);
      }
    } else {
      form.setFieldsValue({
        name: '',
        seo: '',
        cate_name: undefined,
        cate_id: undefined,
        sort: 1,
        manufacturer: [''],
        desc: '',
        avatar: '',
        detail_images: [''],
        is_show: true,
      });
      setAvatarFileList([]);
      setDetailFileList([]);
    }
    setIsDrawerOpen(true);
  };

  const handleOk = async () => {
    try {
      setSubmitLoading(true);
      const values = await form.validateFields();
      // 从文件列表示例生成 detail_images 与 avatar（filename）
      const detailFilenames = (detailFileList || []).map((f) => {
        const respName = f?.response?.filename || f?.response;
        return respName || extractFilename(f?.name || '');
      }).filter((s) => String(s || '').trim());
      // 处理 manufacturer 数组，过滤空值
      const manufacturerArray = (values.manufacturer || [])
        .filter(item => String(item || '').trim())
        .map(item => String(item).trim());
      
      const formData = { 
        ...values, 
        manufacturer: manufacturerArray,
        detail_images: detailFilenames,
        is_show: values.is_show ? 1 : 0,
        cate_id: values.cate_id != null ? Number(values.cate_id) : undefined,
      };

      if (editingDevice && !isCopy) {
        await updateItem({ id: editingDevice.id, ...formData });
        message.success('设备更新成功');
        await fetchList();
      } else {
        await createItem(formData);
        message.success( isCopy ? '设备复制成功' : '设备添加成功');
        setCurrentPage(1);
        await fetchList();
      }
      setIsDrawerOpen(false);
    } catch (err) {
      // 校验或请求失败
      console.log(err);
      
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDelete = async (id) => {
    try {
      setDeletingId(id);
      await deleteItem({ id});
        message.success('设备删除成功');
      const nextPage = list.length === 1 && currentPage > 1 ? currentPage - 1 : currentPage;
      setCurrentPage(nextPage);
      await fetchList();
    } catch (e) {
      message.error('删除失败');
    } finally {
      setDeletingId(null);
    }
  };

  const handleToggleShow = async (record, checked) => {
    try {
      await  showItem({ id: record.id, is_show: checked ? true : false});
      message.success('已更新展示状态');
      await fetchList();
    } catch (e) {
      message.error('更新失败');
    }
  };

  const customUpload = async (options)=>{
    const { onSuccess, onError, file, } = options;
    const formData = new FormData();
    formData.append('image', file);
    const uploadRes =  await uploadImage(formData)
    try {
      if(uploadRes && uploadRes.code === 200 && uploadRes.msg === "success"){
        const filename = uploadRes?.data?.filename || uploadRes?.data;
        onSuccess({ filename }, file);
        message.success(`${file.name} 上传成功`);
        return filename;
      } else {
        const msg = uploadRes?.msg || '未知错误';
        onError('上传失败，错误信息：'+ msg);
        message.error(`${file.name} 上传失败: ${msg}`);
      }
    } catch (err) {
      onError(err);
      message.error(`${file.name} 上传失败`);
    }
  }

  const tableFooter = () => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 16px' }}>
      <span style={{ color: '#666' }}>共 {total} 条记录</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
        <span style={{ color: '#666', fontSize: '12px' }}>每页显示:</span>
        <select value={pageSize} onChange={(e) => { setPageSize(Number(e.target.value)); setCurrentPage(1); }} style={{ padding: '2px 8px', border: '1px solid #d9d9d9', borderRadius: '4px', fontSize: '12px' }}>
          <option value={10}>10</option>
          <option value={20}>20</option>
          <option value={50}>50</option>
          <option value={100}>100</option>
        </select>
      </div>
    </div>
  );

  const columns = [
    { 
      title: '生产商', 
      dataIndex: 'manufacturer', 
      key: 'manufacturer',
      render: (manufacturer) => {
        if (Array.isArray(manufacturer)) {
          return manufacturer.filter(item => String(item || '').trim()).join(', ');
        }
        return manufacturer || '-';
      }
    },
    { title: '设备名称', dataIndex: 'name', key: 'name' },
    { title: '类别', dataIndex: 'cate_name', key: 'cate_name' },
    { title: '关键词', dataIndex: 'seo', key: 'seo', render: (seo) => (
      <div style={{ maxWidth: 200 }}>
        {seo ? String(seo).split(',').map((keyword, index) => (
          <span key={index} style={{ background: '#f0f0f0', padding: '2px 8px', borderRadius: '12px', fontSize: '12px', marginRight: '4px', marginBottom: '4px', display: 'inline-block' }}>{String(keyword).trim()}</span>
        )) : '-'}
      </div>
    )},
    { title: '简介', dataIndex: 'desc', key: 'desc', width: '30%' },
    { title: '排序', dataIndex: 'sort', key: 'sort' },
    {
      title: '展示',
      dataIndex: 'is_show',
      key: 'is_show',
      render: (_, record) => (
        <Switch checked={Number(record.is_show) === 1} onChange={(checked) => handleToggleShow(record, checked)} />
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" icon={<EditOutlined />} onClick={() => showModal(record)}>编辑</Button>
          <Button type="primary" icon={<CopyOutlined />} onClick={() => showModal(record, true)}>复制</Button>
          <Popconfirm title="确认删除该设备吗？" okText="删除" cancelText="取消" onConfirm={() => handleDelete(record.id)}>
            <Button danger icon={<DeleteOutlined />} loading={deletingId === record.id}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Layout>
      <Header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 24px' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <span style={{ color: '#fff', fontSize: 20, fontWeight: '600', marginRight: 16 }}>赛尔缝制设备</span>
          <span style={{ color: '#fff', fontSize: 18 }}>{user?.username || '未登录'}</span>
        </div>
        <Menu mode="horizontal" style={{ background: 'transparent', borderBottom: 'none' }}>
          <Menu.Item key="user" icon={<UserOutlined />}></Menu.Item>
        </Menu>
      </Header>
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>添加</Button>
            <Button icon={<ReloadOutlined />} onClick={() => fetchList()}>刷新</Button>
          </Space>
          <Space>
            <Select
              allowClear
              defaultValue={'all'}
              placeholder="类别筛选"
              style={{ width: 180 }}
              value={filterCateId}
              onChange={(val) => { setFilterCateId(val); setCurrentPage(1); }}
            >
              <Select.Option value={'all'}>全部</Select.Option>
              <Select.Option value={2}>推荐设备</Select.Option>
              <Select.Option value={3}>人物专访</Select.Option>
              <Select.Option value={4}>智能制造专题</Select.Option>
              <Select.Option value={5}>缝前/软件</Select.Option>
              <Select.Option value={6}>缝中</Select.Option>
              <Select.Option value={7}>缝后/物流</Select.Option>
              <Select.Option value={8}>零件电控</Select.Option>
              <Select.Option value={9}>辅助设备</Select.Option>
              <Select.Option value={12}>市场分析报告</Select.Option>
            </Select>
            <Input.Search
              placeholder="搜索关键词"
              allowClear
              enterButton={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={() => { setCommittedKeyword(searchText); setCurrentPage(1); }}
              style={{ width: 300 }}
            />
          </Space>
        </div>
        <Table columns={columns} dataSource={list} loading={loading} rowKey="id" footer={tableFooter} pagination={{ current: currentPage, pageSize: pageSize, total: total, showSizeChanger: false, showQuickJumper: true, showTotal: false, onChange: (page, size) => { setCurrentPage(page); setPageSize(size); }, style: { marginTop: 16, textAlign: 'center' } }} />

        <Drawer
          title={isCopy ? '复制并新建' : editingDevice ? '编辑' : '添加'}
          open={isDrawerOpen}
          maskClosable={false}
          onClose={() => setIsDrawerOpen(false)}
          width={840}
          extra={
            <Space>
              <Button onClick={() => setIsDrawerOpen(false)}>取消</Button>
              <Button type="primary" onClick={handleOk} loading={submitLoading}>确定</Button>
            </Space>
          }
        >
          <Form form={form} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} colon>
            <Typography.Title level={5} style={{ marginTop: 0 }}>基础信息</Typography.Title>
            <Row gutter={16}>
            <Col span={12}>
                <Form.Item name="cate_id" label="类别" rules={[{ required: true, message: '请选择类别' }]} style={{ marginBottom: 12 }}>
                  <Select placeholder="请选择类别" allowClear>
                    <Select.Option value={2}>推荐设备</Select.Option>
                    <Select.Option value={3}>人物专访</Select.Option>
                    <Select.Option value={4}>智能制造专题</Select.Option>
                    <Select.Option value={5}>缝前/软件</Select.Option>
                    <Select.Option value={6}>缝中</Select.Option>
                    <Select.Option value={7}>缝后/物流</Select.Option>
                    <Select.Option value={8}>零件电控</Select.Option>
                    <Select.Option value={9}>辅助设备</Select.Option>
                    <Select.Option value={12}>市场分析报告</Select.Option>
                  </Select>
          </Form.Item>
              </Col>
               <Col span={12}>
                <Form.Item name="name" label={isInterview ? '专访标题' : '设备名称'} rules={[{ required: true, message: '请输入' }]} style={{ marginBottom: 12 }}>
                  <Input allowClear placeholder={isInterview ? '请输入专访标题' : '请输入设备名称'} />
                </Form.Item>
              </Col>
              {isInterview&& <Col span={12}>
                <Form.Item name="username" label={'姓名'} rules={[{ required: true, message: '请输入' }]} style={{ marginBottom: 12 }}>
                  <Input allowClear placeholder={'请输入姓名'} />
                </Form.Item>
              </Col>}
              <Col span={24}>
                <Form.Item label={isInterview ? '单位/职务' : '生产厂商'} labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} style={{ marginBottom: 12 }}>
                  <Form.List name="manufacturer" initialValue={['']}>
                    {(fields, { add, remove }) => (
                      <>
                        {fields.map(({ key, name, ...restField }) => (
                          <div key={key} style={{ display: 'flex', marginBottom: 8, alignItems: 'center' }}>
                            <Form.Item
                              {...restField}
                              name={name}
                              rules={[{ required: true, message: '请输入生产商' }]}
                              style={{ marginBottom: 0, flex: 1, marginRight: 8 }}
                            >
                              <Input 
                                allowClear 
                                placeholder={isInterview ? '请输入单位职务' : '请输入生产商名称'} 
                              />
                            </Form.Item>
                            {fields.length > 1 && (
                              <Button 
                                type="text" 
                                danger 
                                icon={<MinusCircleOutlined />} 
                                onClick={() => remove(name)}
                                style={{ marginLeft: 8 }}
                              />
                            )}
                          </div>
                        ))}
                        <Button 
                          type="dashed" 
                          onClick={() => add('')} 
                          icon={<PlusOutlined />} 
                          style={{ width: '100%' }}
                        >
                          添加{isInterview ? '单位' : '生产厂商'}
                        </Button>
                      </>
                    )}
                  </Form.List>
                </Form.Item>
              </Col>
              
              <Col span={12}>
                <Form.Item name="seo" label="关键词" rules={[{ required: false, message: '请输入关键词' }]} style={{ marginBottom: 12 }}>
                  <Input allowClear placeholder="多个关键词用逗号分隔" />
          </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="sort" label="排序" rules={[{ required: false, message: '请输入排序' }]} style={{ marginBottom: 12 }}>
                  <InputNumber min={1} precision={0} style={{ width: '100%' }} placeholder="数字越小越靠前" />
          </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="is_show" label="展示" valuePropName="checked" style={{ marginBottom: 12 }}>
            <Switch />
          </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item name="desc" label="简介" labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} rules={[{ required: false, message: '请输入简介' }]} style={{ marginBottom: 12 }}>
                  <Input.TextArea rows={3} placeholder="请输入设备简介" />
                </Form.Item>
              </Col>
            </Row>

            <Divider style={{ margin: '12px 0' }} />
            <Typography.Title level={5} style={{ marginTop: 0 }}>图片信息</Typography.Title>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item label="封面图片"  required labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} style={{ marginBottom: 8 }}>
                  {/* 隐藏的表单字段，仅存 filename */}
                  <Form.Item name="avatar" rules={[{ required: true, message: '请上传封面图片' }]} noStyle>
                    <Input style={{ display: 'none' }} />
                  </Form.Item>
                  <Upload
                    listType="picture-card"
                    fileList={avatarFileList}
                    pastable={avatarFileList.length === 0}
                    customRequest={customUpload}
                    onRemove={async () => {
                        setAvatarFileList([]);
                        form.setFieldsValue({ avatar: '' });
                        form.validateFields(['avatar']).catch(() => {});
                      return true;
                    }}
                    onPreview={async (file) => {
                      setAvatarPreviewImage(file.url || '');
                      setAvatarPreviewOpen(true);
                    }}
                    onChange={({ file, fileList }) => {
                      // 仅保留一张
                      const latest = fileList.slice(-1);
                      setAvatarFileList(latest);
                      const filename = file?.response?.filename || file?.response;
                      if (filename) {
                        form.setFieldsValue({ avatar: filename });
                        setAvatarFileList([
                          {
                            uid: '-1',
                            name: filename,
                            status: 'done',
                            url: toAbsoluteUrl(filename),
                          },
                        ]);
                      }
                      form.validateFields(['avatar']).catch(() => {});
                    }}
                  >
                    {avatarFileList.length >= 1 ? null : (
                      <button style={{ border: 0, background: 'none' }} type="button">
                        <PlusOutlined />
                        <div style={{ marginTop: 8 }}>上传</div>
                      </button>
                    )}
                  </Upload>
                  <Form.Item shouldUpdate noStyle>
                    {() => {
                      const errs = form.getFieldError('avatar') || [];
                      return errs.length ? (
                        <div style={{ color: '#ff4d4f', marginTop: 8 }}>{errs[0]}</div>
                      ) : null;
                    }}
                  </Form.Item>
                  {avatarPreviewImage && (
                    <Image
                      wrapperStyle={{ display: 'none' }}
                      preview={{
                        visible: avatarPreviewOpen,
                        onVisibleChange: (visible) => setAvatarPreviewOpen(visible),
                        afterOpenChange: (visible) => !visible && setAvatarPreviewImage(''),
                      }}
                      src={avatarPreviewImage}
                    />
                  )}
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item label="详情图片" labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} style={{ marginBottom: 8 }}>
                  <Upload
                    listType="picture-card"
                    pastable={avatarFileList.length === 1}
                    fileList={detailFileList}
                    customRequest={customUpload}
                    onRemove={async (file) => {
                        const remaining = (detailFileList || []).filter((f) => f.uid !== file.uid);
                        setDetailFileList(remaining);
                        // if (editingDevice && editingDevice.id) {
                        //   try {
                        //     const filenames = remaining
                        //       .map((f) => f?.response?.filename || f?.response || extractFilename(f?.name || ''))
                        //       .filter((s) => String(s || '').trim());
                        //     const payload = buildUpdatePayload({ detail_images: filenames });
                        //     await updateItem({ id: editingDevice.id, ...payload });
                        //     message.success('已移除图片并保存');
                        //   } catch (err) {
                        //     message.error('保存失败，请重试');
                        //   }
                        // }
                      return true;
                    }}
                    onPreview={(file) => {
                      setDetailPreviewImage(file.url || '');
                      setDetailPreviewOpen(true);
                    }}
                    onChange={({ file, fileList }) => {
                      setDetailFileList(fileList);
                    }}
                  >
                    <button style={{ border: 0, background: 'none' }} type="button">
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传</div>
                    </button>
                  </Upload>
                  {detailPreviewImage && (
                    <Image
                      wrapperStyle={{ display: 'none' }}
                      preview={{
                        visible: detailPreviewOpen,
                        onVisibleChange: (visible) => setDetailPreviewOpen(visible),
                        afterOpenChange: (visible) => !visible && setDetailPreviewImage(''),
                      }}
                      src={detailPreviewImage}
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>
        </Form>
        </Drawer>
    </div>
    </Layout>
  );
};

export default DeviceManagement;